import {app, globalShortcut, desktopCapturer, screen}  from "electron"
import {untop,top as camera_top} from './camera.coffee'
import USER from '../user.coffee'
import close from './close.coffee'
import Main from './main.coffee'
import Win from '../win.coffee'
import fullscreen from '../fullscreen.coffee'
import destroy from '../destroy.coffee'
import trayShow, {rec as trayRec} from '../tray.coffee'
import {windowManager} from '@rmw/node-window-manager'

{recbar} = Win

win = undefined


DRAW = undefined
{draw:open_draw} = fullscreen

###
export confirm = (message, buttons)=>
  {response} = await dialog.showMessageBox(
    win
    {
      title: '　'
      message
      buttons
    }
  )
  response
###

export draw = =>
  if DRAW
    return
  DRAW = open_draw()
  DRAW.on 'close',=>
    DRAW = undefined
  draw_top()
  return

export draw_top = =>
  top()
  DRAW.focus()
  return

export draw_x = =>
  destroy(DRAW)
  DRAW = undefined
  return

KEY = [
  'CommandOrControl+R'
  'CommandOrControl+W'
  'CommandOrControl+Q'
  'Alt+F4'
  'F5'
]
DISABLE = {
'browser-window-focus': =>
  for key from KEY
    globalShortcut.register key, =>
      return
  return

'browser-window-blur': =>
  for key from KEY
    globalShortcut.unregister key, =>
      return
  return
}


export 工具条=(src)=>
  if src == 'camera'
    width = 500
  else
    width = 600
  _recbar width

_recbar = (width)=>
  for [key, func] from Object.entries DISABLE
    app.on key,func

  trayRec()
  # https://github.com/electron/electron/issues/5723
  height = 48
  recbar_config = {
    roundedCorners: false
    transparent: true
    resizable: false
    width
    height
  }

  win = recbar recbar_config

  win.on 'close',=>
    win = undefined
  {width:sw,height:sh} =  screen.getPrimaryDisplay().workArea
  win.setBounds {
    x : Math.round((sw - width)/2)
    y : sh - 28 - height
    width
    height
  }
  top()
  camera_top()
  new Promise (resolve)=>
    win.webContents.on(
      'did-finish-load'
      =>
        top()
        win.focus()
        resolve(win)
        return
    )

export top = =>
  if win
    win.setAlwaysOnTop(true,'screen-saver')
    win.moveTop()
  return

export expand = =>
  pos = win.getPosition()
  [nw,nh] = win.getSize()
  [width,height]=win.size
  win.setBounds {
    x:pos[0] + nw - width
    y:pos[1]
    width
    height
  }
  return

export left = =>
  pos = win.getPosition()
  win.size = size = win.getSize()
  width = 162
  height = 48

  ###
  https://github.com/electron/electron/issues/15560
  setSize can't shrink non-resizable window (but can grow it) #15560
  ###
  #win.setMinimumSize(width,height)

  win.setBounds {
    x:pos[0] + size[0] - width
    y:pos[1]
    width
    height
  }
  return


_done = =>
  for [key, func] from Object.entries DISABLE
    app.off key,func
  trayShow()
  untop()
  return

export cancel = =>
  _done()
  close('show')
  return

export end = =>
  _done()
  close()
  return

export hide = =>
  win.hide()
  return


_src = (...types)=>
  desktopCapturer.getSources({
    types
    thumbnailSize: { width: 0, height: 0 }
  })

# desktopCapturer.getSources({ types: ['window', 'screen'] })
# TODO 多屏幕支持
export screen_source = =>
  for i from await _src 'screen'
    return i.id
  return

export win_source = =>
  # TODO 多显示器支持
  #for i from screen.getAllDisplays()
  #  {bounds} = i
  #  if bounds.x == 0
  #    break

  {bounds} = screen.getPrimaryDisplay()

  {scaleFactor} = screen.getPrimaryDisplay()
  id_win = new Map()
  for i from await desktopCapturer.getSources({
    types:['window']
    fetchWindowIcons:false
    thumbnailSize: { width: 320*scaleFactor, height: 180*scaleFactor },
  })
    id_win.set(
      Math.floor(i.id.split(":")[1])
      [
        i.thumbnail.toDataURL()
        i.name
      ]
    )

  r = []
  for i from windowManager.getWindows()
    {id} = i
    if not process.execPath.startsWith(i.path)
      li = id_win.get(id)
      if li
        {x,y,width,height} = i.getBounds()
        if (x+width)<=0 and x<=0
          continue
        if (x+width)>bounds.width and x>bounds.width
          continue
        if (y+height)<=0 and y<=0
          continue
        if (y+height)>bounds.height and y>bounds.height
          continue

        w = bounds.width - x
        if width > w
          width = w
        h = bounds.height - y
        if height > h
          height = h
        if x<0
          x=0
        if y<0
          y=0

        r.push li.concat [id,x,y,width,height]

  return r

export stop = (is_camera)=>
  #user_id = await win.webContents.executeJavaScript('localStorage.user_id', true)
  BrowserWindow.getAllWindows().forEach(
    (w)=>
      {hash} = new URL w.webContents.getURL()
      if not is_camera
        if hash[1..] == 'camera'
          destroy w
          return

      w.hide()
  )
  return
